<template>
  <el-dialog v-model="dialogFormVisible" title="请输入会议室信息" @close="closeFn">
    <el-form :model="form">
      <el-form-item label="会议室名称" :label-width="formLabelWidth">
        <el-input v-model="form.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="会议室人数" :label-width="formLabelWidth">
        <el-input v-model="form.number" autocomplete="off" />
      </el-form-item>
      <el-form-item label="配置" :label-width="formLabelWidth">
        <el-input v-model="form.config" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitFn">
          提交
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { reactive, ref, watch, watchEffect } from 'vue';
// 接收父组件传入的属性和自定义事件
const props = defineProps(["formVisible", "formData", "type"]);
const emits = defineEmits(["changeVisible", "submit"]);

// 表单数据
const form = reactive({
  id: props.formData.id,
  name: props.formData.name,
  number: props.formData.number,
  config: props.formData.config
})

// 侦听表单提交状态（添加）和弹出框的显示状态
watchEffect(()=>{
  if(props.type === 0 && props.formVisible){
    // 如果弹出框显示，且状态为添加，清空表单数据
    form.name = "";
    form.number = "";
    form.config = "";
  }
})
// 侦听表单数据
watch(()=>props.formData, (v)=>{
  // 根据父组件传入的最新数据，更新表单内容
  form.id = v.id;
  form.name = v.name;
  form.number = v.number;
  form.config = v.config;
},{
  deep: true
})

const formLabelWidth = "140px";

// 弹出框的显示隐藏状态
const dialogFormVisible = ref(false);
// 根据父组件传入的状态切换
watch(()=>props.formVisible, (v)=>{
  if(!v) return;
  dialogFormVisible.value = v;
});
// 关闭弹出框时要执行的功能：通知父组件最新状态
function closeFn(){
  emits("changeVisible", false);
}

// 点击表单提交按钮时的功能
const submitFn = function(){
  if(!form.name || !form.number || !form.config){
    return;
  }
  dialogFormVisible.value = false;
  // 执行父组件传入的提交功能（添加或修改或其他）
  // 同时将表单数据发送给父组件
  emits("submit", form);
}
</script>

<style scoped>
.el-button--text {
  margin-right: 15px;
}
.el-select {
  width: 300px;
}
.el-input {
  width: 300px;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
